package lossy;

import java.util.ArrayList;
import java.util.List;

public class ZeroHandler {
	public static double[][] encode(double[][] in){
		double[][] out = new double[in.length][in.length];
		
		for(int i = 0; i < in.length; i++){
			int j = 0;
			int zeroCounter = 0;
			
			while(j < in[i].length){
//				if(DCT.getRed((int)in[i][j]) == 0){
				System.out.println(((int) in[i][j]) == 0 );
				if(((int) in[i][j]) == 0 ){
					zeroCounter++;
					if(j == in[i].length -1){
						if(zeroCounter > 1){
//							out[i][j - zeroCounter + 1] = DCT.mixColor(0, 0, 0);
							out[i][j - zeroCounter + 1] = 0;
							out[i][j - zeroCounter + 2] = zeroCounter;
							for(int a = 0; a < zeroCounter - 2; a++){
								out[i][j - zeroCounter + 3 + a] = 666;
							}
						} else if(zeroCounter == 1){
//							out[i][j-1] = DCT.mixColor(0, 0, 0);
							out[i][j - 1] = 0;
						}
						zeroCounter = 0;
					}
				} else {
					if(zeroCounter > 1){
//						out[i][j - zeroCounter + 1] = DCT.mixColor(0, 0, 0);
						out[i][j - zeroCounter + 1] = 0;
						out[i][j - zeroCounter + 2] = zeroCounter;
						for(int a = 0; a < zeroCounter - 2; a++){
							out[i][j - zeroCounter + 3 + a] = 666;
						}
					} else if(zeroCounter == 1){
//						out[i][j-1] = DCT.mixColor(0, 0, 0);
						out[i][j - 1] = 0;
					}
					zeroCounter = 0;
					out[i][j] = in[i][j];
				}
				j++;
			}
		}
		
		return out;
	}
	
	public static double[][] decode(double[][] in, int n){
		double[][] out = new double[n][n];
		for(int i = 0; i < n; i++){
			int j = 0;
			int y = 0;
			while(y < in[i].length && j < n){
				if( j < n-1 && y < in[i].length - 1 && DCT.getRed((int)in[i][y]) == 0 ){
					out[i][j] = in[i][y];
					j++;
					y++;
					if(j < n ){
						int counter = (int)in[i][y];
						for(int a = 1; a < counter && j < n; a++){
							out[i][j] = DCT.mixColor(0, 0, 0);
							j++;
						}
					}
				} else {
					out[i][j] = in[i][y];
					j++;
				}
				y++;
			}
		}
		
		return out;
	}
	
	public static double[][] trimZeros(double[][] in, int n){
		Double[][] out = new Double[n][];
		
		for(int i = 0; i < n; i++){
			List<Double> list = new ArrayList<>();
			int j = 0;
			while(j < in[i].length){
				if((int)in[i][j] != 666){
					list.add(in[i][j]);
				}
				j++;
			}
			out[i] = list.toArray(new Double[list.size()]);
		}
		double[][]result = new double[n][];
		for(int i = 0; i < n; i++){
			result[i] = new double[out[i].length];
			for(int j = 0; j < out[i].length; j++){
				result[i][j] = out[i][j];
			}
		}
		
		return result;
	}
}
